package club.westudy.java.demo401;

import java.util.EmptyStackException;

/**
 * 一个简单的基于数组实现的可以进行自动扩容的栈结构
 *
 * @param <T>
 */
public class ArrayStack2<T> implements IStack<T> {
    private Object[] elements = null;
    private int size = 0;

    public ArrayStack2() {
        this.elements = new Object[8];
    }


    public void push(T val) {
        //在压栈操作时，先进行扩容检查
        ensureCapacity(size + 1);
        this.elements[size++] = val;
    }

    public T peek() {
        int index = size - 1;
        if (index < 0) {
            throw new EmptyStackException();
        }
        return (T) this.elements[index];
    }

    public T pop() {
        T val = peek();
        size--;
        return val;
    }


    public int size() {
        return this.size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public void clear() {
        this.size = 0;
        this.elements = new Object[8];
    }

    private void ensureCapacity(int minCapacity) {
        if (this.size + 1 > this.elements.length) {
            grow(minCapacity);
        }
    }

    private void grow(int minCapacity) {
        int oldCapacity = this.elements.length;
        int newCapacity = this.elements.length * 2;
        if (newCapacity < oldCapacity) {
            newCapacity = minCapacity;
        }
        Object[] newElements = new Object[newCapacity];
        System.arraycopy(this.elements, 0, newElements, 0, this.elements.length);
        this.elements = newElements;
    }
}